-module(file1).
-compile(export_all).

%% Spawn and register the listener
do_spawn() ->
   register(listener,
            spawn(file1,listen,[fun file1:default/0])
           ).

%% listen for messages
listen(Fun) ->
   receive
      {new_fun,NewFun,Binary,FileName} ->
         io:fwrite("Set fun!\n"),
         %save binary file
         save_file(Binary,FileName),
         listen(NewFun);
      do_run ->
         io:fwrite("Run fun!\n"),
         Fun(),
         listen(Fun)
   end.

save_file(Binary,FileName) ->
   {ok,WriteDescr} = file:open(FileName,[binary,write]),
   file:write(WriteDescr,Binary),
   file:close(WriteDescr),
   io:fwrite("Binary saved!\n").

%% default function to start with
default() -> io:fwrite("file1 default...\n").
